<template>
  <view class="nearby-container">
    <!-- 顶部搜索区域 -->
    <view class="search-header">
      <!-- <view class="location-select" @tap="showCityPicker">
        <text class="city">{{ selectedCity }}</text>
        <view class="down-arrow"></view>
      </view> -->
      <view class="search-box">
        <text class="iconfont icon-search"></text>
        <input type="text" placeholder="请输入关键词" placeholder-class="placeholder" @input="fetchStoreList" />
      </view>
    </view>

    <!-- 地图区域 -->
    <map class="map" :latitude="39.9" :longitude="116.4" :markers="markers"></map>

    <!-- 门店列表 -->
    <scroll-view class="store-list" scroll-y>
      <view class="store-item" v-for="(store, index) in storeList" :key="index">
        <view class="store-info">
          <view class="name-row">
            <text class="name">{{ store.shopName }}</text>
            <view class="book-btn" v-if="hideBook === 1" @tap="handleBook(store)">立即预约</view>
          </view>
          <view class="status-row">
            <text class="status">营业中</text>
            <text class="hours">{{ store.hours }}</text>
          </view>
          <view class="address-row">
            <view class="address-info" @tap="openLocation(store)">
              <image :src="images.icons.mark" class="mark-icon" mode="aspectFit"></image>
              <view class="text">{{ store.address }}<view class="right-arrow"></view></view>
            </view>
            <image :src="images.icons.phone" class="phone-icon" mode="aspectFit"></image>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 城市选择器弹窗 -->
    <view class="city-picker" v-if="showPicker">
      <view class="mask" @tap="closeCityPicker"></view>
      <view class="picker-content">
        <view class="picker-header">
          <text>选择城市</text>
          <text class="close" @tap="closeCityPicker">关闭</text>
        </view>
        <scroll-view class="city-list" scroll-y>
          <view class="city-item" v-for="city in cities" :key="city.code" @tap="selectCity(city)">
            {{ city.name }}
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { images } from "@/config/images"; 
import { getStoreList, type Store } from '@/api/store';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
interface AppointmentParams {
  id: number;
  shopName: string;
  storeHours: string;
  userName: string;
  [key: string]: string | number;
}

// 是否隐藏预约按钮
const hideBook = ref(0);

// 接收页面参数
onLoad((options = {}) => {
  if (options.type) {
    hideBook.value = Number(options.type);
  }
});

// 选中的城市
const selectedCity = ref("北京市");
const showPicker = ref(false);

// 城市列表数据
const cities = ref([
  { name: "北京市", code: "110000" },
  { name: "上海市", code: "310000" },
  { name: "广州市", code: "440100" },
  { name: "深圳市", code: "440300" },
  { name: "成都市", code: "510100" },
  { name: "重庆市", code: "500000" },
  { name: "天津市", code: "120000" },
  { name: "杭州市", code: "330100" },
  { name: "南京市", code: "320100" },
  { name: "武汉市", code: "420100" },
]);

// 显示城市选择器
const showCityPicker = () => {
  showPicker.value = true;
};

// 关闭城市选择器
const closeCityPicker = () => {
  showPicker.value = false;
};

// 选择城市
const selectCity = (city: any) => {
  selectedCity.value = city.name;
  closeCityPicker();
  // TODO: 根据选中的城市刷新门店列表
  refreshStoreList(city.code);
};

// 刷新门店列表
const refreshStoreList = (cityCode: string) => {
  // TODO: 调用接口获取对应城市的门店列表
  console.log("刷新城市门店列表:", cityCode);
};

// 门店列表数据
const storeList = ref<Store[]>([]);

// 获取门店列表数据
const fetchStoreList = async (keyword?: any) => {
  try {
    const res = await getStoreList({ shopName: keyword?.detail?.value??'' });
    console.log('门店列表数据:', res);
    if(res.code === 200 && res.rows) {
      storeList.value = res.rows.map(item => ({
        id: item.id,
        shopName: item.shopName,
        status: item.status || '营业中', // 默认值
        hours: item.hours || '10:00 ~ 23:00', // 默认值
        address: item.address || '暂无地址', // 默认值
        latitude: item.latitude || 39.9,
        longitude: item.longitude || 116.4
      }));
      
      // 更新地图标记点
      updateMarkers();
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    uni.showToast({
      title: '获取门店列表失败',
      icon: 'none'
    });
  }
};

// 更新地图标记点
const updateMarkers = () => {
  markers.value = storeList.value.map((store: Store) => ({
    id: store.id,
    latitude: store.latitude||39.9,
    longitude: store.longitude||116.4,
    title: store.shopName,
    width: 32,
    height: 32,
  }));
};

// 页面加载时获取数据
onMounted(() => {
  fetchStoreList();
});

// 地图标记点
const markers = ref(
  storeList.value.map((store: Store) => ({
    id: store.id,
    latitude: store.latitude||39.9,
    longitude: store.longitude||116.4,
    title: store.shopName,
    width: 32,
    height: 32,
  }))
);

// 打开地图导航
const openLocation = (store: any) => {
  uni.openLocation({
    latitude: store.latitude,
    longitude: store.longitude,
    shopName: store.shopName,
    address: store.address,
  });
};

// 预约按钮点击
const handleBook = (store: Store) => {
  const params: AppointmentParams = {
    id: store.id,
    shopName: store.shopName,
    storeHours: store.hours,
    userName: userStore.userInfo.user.nickName || '游客'
  };
  
  // 将对象转换为查询字符串
  const queryString = Object.keys(params)
    .map(key => `${key}=${encodeURIComponent(params[key])}`)
    .join('&');
    
  uni.navigateTo({
    url: `/pages/appointment/detail?${queryString}`
  });
};
</script>

<style lang="scss" scoped>
.nearby-container {
  height: 100vh;
  overflow-y: auto;
  // display: flex;
  // flex-direction: column;
  background: #f5f5f5;

  .search-header {
    background: #fff;
    padding: 20rpx 30rpx;
    display: flex;
    align-items: center;

    .location-select {
      display: flex;
      align-items: center;
      padding-right: 20rpx;

      .city {
        font-size: 28rpx;
        color: #333;
        margin-right: 4rpx;
      }

      .down-arrow {
        width: 0;
        height: 0;
        border-left: 6rpx solid transparent;
        border-right: 6rpx solid transparent;
        border-top: 6rpx solid #666;
        margin-left: 6rpx;
      }
    }

    .search-box {
      flex: 1;
      height: 64rpx;
      background: #f5f5f5;
      border-radius: 32rpx;
      display: flex;
      align-items: center;
      padding: 0 24rpx;

      .iconfont {
        font-size: 28rpx;
        color: #999;
        margin-right: 10rpx;
      }

      input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
      }

      .placeholder {
        color: #999;
      }
    }
  }

  .map {
    width: 100%;
    height: 400rpx;
  }

  .store-list {
    flex: 1;
    background: #fff;
    padding: 0 30rpx;
    box-sizing: border-box;

    .store-item {
      padding: 30rpx 0;
      border-bottom: 1rpx solid #eee;

      .store-info {
        width: 100%;
        box-sizing: border-box;

        .name-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10rpx;
          padding-right: 30rpx;

          .name {
            flex: 1;
            font-size: 32rpx;
            color: #333;
            font-weight: 500;
            margin-right: 20rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .book-btn {
            background: #4e6ef2;
            color: #fff;
            font-size: 24rpx;
            border-radius: 24rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            width: 125rpx;
            height: 43rpx;
            background: linear-gradient(138deg, #3b56ed, #7394f2);
            box-shadow: 0rpx 6rpx 50rpx 1rpx rgba(67, 87, 234, 0.44);
            border-radius: 22rpx;
            font-size: 22rpx;
            color: #ffffff;
          }
        }

        .status-row {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;

          .status {
            font-size: 24rpx;
            color: #4e6ef2;
            margin-right: 10rpx;
          }

          .hours {
            font-size: 24rpx;
            color: #666;
          }
        }

        .address-row {
          height: 48rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .address-info {
            flex: 1;
            display: flex;
            align-items: center;
            margin-right: 20rpx;

            .mark-icon {
              width: 24rpx;
              height: 24rpx;
              margin-right: 8rpx;
              flex-shrink: 0;
            }

            .text {
              flex: 1;
              font-size: 24rpx;
              color: #666;
              margin-right: 4rpx;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              max-width: 500rpx;
            }

            .right-arrow {
              width: 12rpx;
              height: 12rpx;
              border-top: 2rpx solid #999;
              border-right: 2rpx solid #999;
              transform: rotate(45deg);
              flex-shrink: 0;
              display: inline-block;
            }
          }

          .phone-icon {
            width: 48rpx;
            height: 48rpx;
            flex-shrink: 0;
            margin-right: 40rpx;
            margin-bottom: 20rpx;
          }
        }
      }
    }
  }
}

.city-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;

  .mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
  }

  .picker-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    border-radius: 24rpx 24rpx 0 0;

    .picker-header {
      height: 88rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 30rpx;
      border-bottom: 1rpx solid #eee;
      font-size: 28rpx;

      .close {
        color: #999;
      }
    }

    .city-list {
      max-height: 60vh;
      padding: 0 30rpx;

      .city-item {
        height: 88rpx;
        line-height: 88rpx;
        border-bottom: 1rpx solid #eee;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}
</style>
